<template>
  <div class="common_wrap">
    <div class="common_title">重点关注任务管理</div>
    <!-- 搜索表单 -->
    <el-form
      ref="queryForm"
      :model="queryParams"
      label-width="100px"
      inline
      class="search-nav"
    >
      <el-form-item prop="title" label="批示标题：">
        <el-input
          v-model="queryParams.title"
          maxlength="255"
          placeholder="请输入批示标题"
          clearable
        ></el-input>
      </el-form-item>
      <el-form-item prop="date" label="批示时间：">
        <el-date-picker
          v-model="queryParams.date"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          value-format="yyyy-MM-dd"
          clearable
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item prop="status" label="状态：">
        <el-select v-model="queryParams.status" placeholder="请选择状态">
          <el-option
            v-for="(item, index) in statusList"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item prop="issueId" label="下发人：">
        <el-select
          v-model="queryParams.issueId"
          filterable
          clearable
          placeholder="请选择下发人"
        >
          <el-option
            v-for="(item, index) in issueList"
            :key="index"
            :label="item.name"
            :value="item.empId"
          ></el-option>
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="getTableData"
          >查询</el-button
        >
        <el-button
          type="primary"
          plain
          icon="el-icon-refresh"
          @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <div class="btn_group">
      <el-button type="primary" @click="exportTask">导出统计</el-button>
      <el-button type="primary" @click="addTask">添加批示任务</el-button>
      <el-button type="primary" @click="addRole">重点任务查看权限</el-button>
    </div>
    <!-- 表格 -->
    <el-table :data="tableData" style="width: 100%; margin-top: 24px">
      <el-table-column prop="id" label="ID" width="80"> </el-table-column>
      <el-table-column prop="title" label="批示标题" show-overflow-tooltip>
      </el-table-column>
      <el-table-column prop="redCount" label="红牌数" width="80">
      </el-table-column>
      <el-table-column prop="greenCount" label="绿牌数" width="80">
      </el-table-column>
      <el-table-column prop="issueTime" label="批示时间" width="200">
      </el-table-column>
      <!-- <el-table-column prop="issueName" label="下发人"> </el-table-column>
      <el-table-column label="职务">
        <template slot-scope="scope">
          <div>{{ scope.row.issueArea }} {{ scope.row.issuePost }}</div>
        </template>
      </el-table-column> -->
      <el-table-column label="状态" width="80">
        <template slot-scope="scope">
          <div>
            {{
              scope.row.status === 1
                ? "已下发"
                : scope.row.status === 2
                ? "已撤回"
                : "未下发"
            }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="160">
        <template slot-scope="scope">
          <el-tooltip
            content="查看详情"
            placement="top"
            v-if="scope.row.status === 1"
          >
            <el-button
              type="primary"
              icon="el-icon-document"
              circle
              @click="detail(scope.row)"
            />
          </el-tooltip>
          <el-tooltip
            content="撤回"
            placement="top"
            v-if="scope.row.status === 1"
          >
            <el-button
              type="primary"
              icon="el-icon-back"
              circle
              @click="back(scope.row)"
            />
          </el-tooltip>

          <el-tooltip
            content="编辑"
            placement="top"
            v-if="scope.row.status !== 1"
          >
            <el-button
              type="primary"
              icon="el-icon-edit"
              circle
              @click="edit(scope.row)"
            />
          </el-tooltip>

          <el-tooltip
            content="任务管理"
            placement="top"
            v-if="scope.row.status !== 1"
          >
            <el-button
              type="primary"
              icon="el-icon-s-custom"
              circle
              @click="management(scope.row)"
            />
          </el-tooltip>

          <el-tooltip
            content="下发任务"
            placement="top"
            v-if="scope.row.status !== 1"
          >
            <el-button
              type="primary"
              icon="el-icon-s-promotion"
              circle
              @click="send(scope.row)"
            />
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页器 -->
    <el-pagination
      class="pagination-container"
      v-if="tableData.length"
      :background="true"
      :current-page="queryParams.pageNo"
      :page-sizes="[10, 20, 30, 40, 50]"
      :page-size="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="sizeChange"
      @current-change="currentChange"
    />
    <el-dialog title="添加批示任务" :visible.sync="dialogVisible" width="50%">
      <el-form
        ref="task"
        :model="task"
        label-width="100px"
        class="search-nav"
        :rules="taskRules"
      >
        <el-form-item prop="title" label="标题：">
          <el-input
            v-model="task.title"
            maxlength="255"
            placeholder="请输入批示标题"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item prop="issueTime" label="批示时间：">
          <el-date-picker
            v-model="task.issueTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item prop="content" label="内容：">
          <el-input
            v-model="task.content"
            type="textarea"
            maxlength="255"
            placeholder="请输入批示内容"
            clearable
          ></el-input>
        </el-form-item>
        <!-- <el-form-item prop="issueId" label="下发人：">
          <el-select
            v-model="task.issueId"
            filterable
            clearable
            placeholder="请选择下发人"
          >
            <el-option
              v-for="(item, index) in issueList"
              :key="index"
              :label="item.name"
              :value="item.empId"
            >
            </el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="附件：" prop="annexPath" class="is-required">
          <el-upload
            ref="upload"
            class="upload-demo"
            :headers="headers"
            :action="actionUrl"
            :limit="fileLimit"
            :on-success="successUp"
            :on-error="errorUp"
            :on-remove="deleteFile"
            :before-upload="beforeUpload"
            :file-list="defaultList"
          >
            <el-button ref="files" size="small" type="primary"
              >选取文件</el-button
            >
            <div slot="tip" class="el-upload__tip">
              支持文件格式：.pdf、.doc、.docx、.jpg、.jpeg、.png，单次上传文件限制大小100MB。
            </div>
          </el-upload>
          <!-- <div v-for="(item, index) in fileList" :key="index">
            <div>{{ item.fileName }}</div>
            <div>{{ item.url }}</div>
          </div> -->
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelTask">取 消</el-button>
        <el-button type="primary" @click="submitTask">确 定</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="重点关注任务查看权限"
      :visible.sync="roleVisible"
      width="30%"
    >
      <el-form>
        <el-form-item label="人员：">
          <el-select
            v-model="issueIdList"
            filterable
            clearable
            multiple
            placeholder="请选择人员"
          >
            <el-option
              v-for="(item, index) in issueList"
              :key="index"
              :label="
                item.name +
                ' ' +
                (item.areaName || '') +
                ' ' +
                (item.positionName || '')
              "
              :value="item.empId"
            >
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="roleVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitRole">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>


<script>
export default {
  name: "MarketManage",
  data() {
    return {
      issueIdList: [],
      queryParams: {
        title: "",
        date: [],
        pageNo: 1,
        pageSize: 10,
        status: null,
      },
      issueList: [],
      tableData: [],
      total: 0,
      dialogVisible: false,
      roleVisible: false,
      task: {
        title: "",
        content: "",
        // issueId: "",
        annexName: "",
        annexPath: "",
      },
      taskRules: {
        title: [{ required: true, message: "请输入批示标题", trigger: "blur" }],
        issueTime: [
          { required: true, message: "请选择批示时间", trigger: "blur" },
        ],
        content: [
          { required: true, message: "请输入批示内容", trigger: "blur" },
        ],
        // issueId: [{ required: true, message: "请选择下发人", trigger: "blur" }],
        annexPath: [
          { required: true, message: "请上传附件", trigger: "change" },
        ],
      },
      headers: {
        Authorization: "Bearer " + localStorage.getItem("token"),
      },
      fileList: [],
      defaultList: [],
      fileLimit: 1,
      statusList: [
        {
          label: "未下发",
          value: 0,
        },
        {
          label: "已下发",
          value: 1,
        },
        {
          label: "已撤回",
          value: 2,
        },
      ],
    };
  },
  computed: {
    actionUrl() {
      return process.env.VUE_APP_BASE_URL + "/file/upload";
    },
  },
  created() {
    this.getIssueList();
    this.getTableData();
  },
  methods: {
    exportTask() {
      window.open(
        process.env.VUE_APP_BASE_URL + "/dutiesAdmin/export",
        "_blank"
      );
    },
    addRole() {
      this.roleVisible = true;
      this.getIssueRoleList();
    },
    // 新增批示任务
    addTask() {
      this.dialogVisible = true;
    },
    // 编辑
    edit(data) {
      console.log(data);
      this.task = JSON.parse(JSON.stringify(data));
      this.fileList[0] = {
        id: this.task.id,
        fileName: this.task.annexName,
        url: this.task.annexPath,
      };
      this.defaultList = [
        {
          id: this.task.id,
          name: this.task.annexName,
          url: this.task.annexPath,
        },
      ];
      this.$nextTick(() => {
        this.$refs.upload.submit();
      });

      this.dialogVisible = true;
    },
    // 任务管理
    management(item) {
      this.$router.push({
        path: "/marketManageAdd",
        query: {
          parentId: item.id,
          parentTitle: item.title,
        },
      });
    },
    // 撤回
    back(data) {
      this.$confirm("确定撤回吗？", "撤回").then(() => {
        this.$api
          .backTask({
            id: data.id,
          })
          .then((res) => {
            if (res.status === 200) {
              this.$message.success("撤回任务成功");
              this.getTableData();
            } else {
              this.$message.error("撤回任务失败");
            }
          })
          .catch((res) => {
            this.$message.error("撤回任务失败");
          });
      });
    },
    // 下发
    send(data) {
      this.$confirm("确定下发吗？", "下发").then(() => {
        this.$api
          .sendTask({
            id: data.id,
          })
          .then((res) => {
            if (res.status === 200) {
              this.$message.success("下发任务成功");
              this.getTableData();
            } else {
              this.$message.error("下发任务失败");
            }
          })
          .catch((res) => {
            this.$message.error("下发任务失败");
          });
      });
    },
    // 详情
    detail(data) {
      this.$router.push({
        path: "/marketManageDetail",
        query: {
          ...data,
        },
      });
    },
    // 保存批示任务
    submitTask() {
      // 如果有文件  则赋值  方便通过表单校验 :)
      if (this.fileList.length) {
        this.task.annexName = this.fileList[0].fileName;
        this.task.annexPath = this.fileList[0].url;
      }
      // 表单校验
      this.$refs.task.validate(async (valid) => {
        if (!valid) return;
        // 别问
        this.task.issueTime += " 00:00:00";
        //
        if (this.task.id) {
          this.$api.editTask(this.task).then((res) => {
            if (res.status === 200) {
              this.getTableData();
              this.task = {
                title: "",
                content: "",
                annexName: "",
                annexPath: "",
              };
              this.$message.success("编辑成功");

              this.dialogVisible = false;
            }
          });
        } else {
          this.$api.addTask(this.task).then((res) => {
            if (res.status === 200) {
              this.getTableData();
              this.task = {
                title: "",
                content: "",
                annexName: "",
                annexPath: "",
              };
              this.$message.success("新增成功");
              this.dialogVisible = false;
            }
          });
        }
      });
    },
    cancelTask() {
      this.task = {
        title: "",
        content: "",
        // issueId: "",
        annexName: "",
        annexPath: "",
      };
      this.dialogVisible = false;
    },
    getIssueList() {
      this.$api
        .roleAllList({
          page: 1,
          limit: 9999,
          type: 1,
        })
        .then((res) => {
          if (res.status === 200) {
            this.issueList = res.data.data.items;
          }
        });
    },
    getIssueRoleList() {
      this.$api.roleList().then((res) => {
        if (res.status === 200) {
          this.issueIdList = res.data.data.map((v) => v.empId);
        }
      });
    },
    submitRole() {
      // http...
      this.$api.saveRoleList(this.issueIdList).then((res) => {
        if (res.status === 200) {
          this.$message.success("保存成功");
          this.getTableData();
          this.roleVisible = false;
        }
      });
    },
    getTableData() {
      if (this.queryParams.date && this.queryParams.date.length) {
        this.queryParams.startTime = this.queryParams.date[0];
        this.queryParams.endTime = this.queryParams.date[1];
      }
      this.$api.taskList(this.queryParams).then((res) => {
        if (res.status === 200) {
          this.tableData = res.data.records;
          this.total = res.data.total;
        } else {
          this.tableData = [];
        }
      });
    },
    resetQuery() {
      this.queryParams = {
        title: "",
        date: [],
        // issueId: "",
        pageNo: 1,
        pageSize: 10,
      };
      this.getTableData();
    },
    // 每页显示数量变化
    sizeChange(size) {
      this.queryParams.pageSize = size;
      this.queryParams.pageNo = 1;
      this.getTableData();
    },
    // 当前页变化
    currentChange(current) {
      this.queryParams.pageNo = current;
      this.getTableData();
    },
    successUp(res, file) {
      this.fileList.push({ id: file.uid, ...res });
    },
    deleteFile(file) {
      console.log(file);
      this.fileList = this.fileList.filter((item) => {
        return file.uid != item.id && file.id != item.id;
      });

      // 防止误操作  导致文件还存在 ┐(ﾟ～ﾟ)┌
      Object.assign(this.task, {
        annexName: "",
        annexPath: "",
      });
    },
    errorUp() {
      this.loading.close();
      this.$alert("文件导入失败", "导入结果", {
        type: "error",
      });
    },
    beforeUpload(file) {
      const fileName = file.name;
      const reg = /(.pdf|.word|.jpg|.jpeg|.doc|.docx|.png)$/;
      if (!reg.test(fileName)) {
        this.$message.error(
          "请上传.pdf、.doc、.docx、.jpg、.jpeg、.png格式的文件"
        );
        return false;
      }
    },
  },
};
</script>


<style scoped>
.btn_group {
  display: flex;
  justify-content: flex-end;
}
</style>